﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Drawing.Printing;
using System.Drawing.Imaging;
using System.IO;

namespace CalemShop
{
    public partial class FrmSale : Form
    {
        string masoHD = string.Empty;
        decimal totalMoneyInBill = 0;
        DataTable invoiceData = new DataTable();
        PrintDocument doc = new PrintDocument();
        Font fontBody = new Font("Verdana", 11);
        Font fontHeader = new Font("Verdana", 11, FontStyle.Bold);
        Font fontFooter = new Font("Verdana", 9);
        Font fontFooterBold = new Font("Verdana", 9, FontStyle.Bold);
        Hashtable itemRowCache = new Hashtable();
        Hashtable itemCache = new Hashtable();
        ItemEntity currentSelectedItem = null;
        public FrmPrintBillPreview frmPrintView = null;
        bool isActiveFrom = true;
        private Customer currentCustomer = null;

        public FrmSale()
        {
            InitializeComponent();
            cbMaSo.KeyUp += new KeyEventHandler(cbMaSo_KeyUp);
            cbMaSoMoi.KeyUp += new KeyEventHandler(cbMaSo_KeyUp);
            doc.PrintPage += new PrintPageEventHandler(doc_PrintPage);
            addAutoNumFormat();
        }

        void cbMaSo_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Control c = (Control)sender;
                if (c.Name.Equals(cbMaSoMoi.Name))
                {
                    doAddInvoiceRow(true);
                }
                else
                {
                    doAddInvoiceRow(false);
                }
            }
        }

        private void FrmSale_Load(object sender, EventArgs e)
        {
            invoiceData.Columns.Add("itemId", Type.GetType("System.String"));
            invoiceData.Columns.Add("itemName", Type.GetType("System.String"));
            invoiceData.Columns.Add("amount", Type.GetType("System.Int32"));
            invoiceData.Columns.Add("price", Type.GetType("System.Int32"));
            invoiceData.Columns.Add("money", Type.GetType("System.Decimal"));
            invoiceData.Columns.Add("ck", Type.GetType("System.Decimal"));
            invoiceData.Columns.Add("autoKey", Type.GetType("System.Int32"));
            bindingSource.DataSource = invoiceData;
            cbSeller.DataSource = Database.getUserList();
            initData();
        }

        public void initData()
        {
            loadItemIds();
        }

        private void doProcessStaffSeller(string sellerCode)
        {
            try
            {
                ArrayList list = (ArrayList)cbSeller.DataSource;
                Staff seller = Database.getUserBySerial(sellerCode);
                if (seller != null)
                {
                    foreach (string acc in list)
                    {
                        if (string.Compare(acc, seller.name, true) == 0)
                        {
                            cbSeller.SelectedText = seller.name;
                            cbSeller.SelectedItem = acc;
                            break;
                        }
                    }
                }
            }
            catch (Exception e) { }
        }

        private void doProcessCustomerService(string customerCode)
        {
            currentCustomer = Database.getCustomerBySerial(customerCode);
            if (currentCustomer != null)
            {
                txtCustomer.Text = " Khách hàng:" + currentCustomer.customerName.ToUpper();
                if (customerCode.StartsWith("CB."))
                {
                    checkCK.Enabled = true;
                    checkCK.Checked = true;
                    txtCK.Value = 15;
                } if (customerCode.StartsWith("CG."))
                {
                    checkCK.Enabled = true;
                    checkCK.Checked = true;
                    txtCK.Value = 10;
                } if (customerCode.StartsWith("CW."))
                {
                    checkCK.Enabled = true;
                    checkCK.Checked = true;
                    txtCK.Value = 5;
                }
            }
        }

        private void addAutoNumFormat()
        {
            foreach (Control c in groupBox1.Controls)
            {
                if (c.Tag != null && string.Compare(c.Tag.ToString(), "number", true) == 0)
                {
                    c.KeyUp += new KeyEventHandler(c_KeyUp);
                    c.KeyPress += new KeyPressEventHandler(c_KeyPress);
                }
            }

            //txtCustomerMoney.KeyUp += new KeyEventHandler(c_KeyUp);
            //txtCustomerMoney.KeyPress += new KeyPressEventHandler(c_KeyPress);
        }

        void loadItemIds()
        {
            cbMaSo.AutoCompleteCustomSource = Database.getAllItemIds();
            cbMaSoMoi.AutoCompleteCustomSource = Database.listItemAutoKeys;
        }

        void c_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
        }



        void c_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                //MessageBox.Show(e.KeyCode.ToString());

                if ((e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9) || (e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9))
                {
                    TextBox control = (TextBox)sender;
                    string value = control.Text.Replace(@".", "");
                    int num;
                    Int32.TryParse(value, out num);
                    string s = num.ToString("#,0");
                    control.Text = s;
                    control.SelectionStart = s.Length + 1;
                    //if (string.Compare(control.Name, "txtCustomerMoney") == 0 && !string.IsNullOrEmpty(txtTotal.Text))
                    //{
                    //    string sTotal = txtTotal.Text.Replace(@".", "");
                    //    long total = long.Parse(sTotal);
                    //    if (num > total)
                    //    {
                    //        long returnMoney = num - total;
                    //        txtMoneyReturn.Text = returnMoney.ToString("#,0");
                    //    }
                    //}
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void FrmSale_FormClosing(object sender, FormClosingEventArgs e)
        {
            FrmMain frmMain = (FrmMain)this.MdiParent;
            frmMain.frmSale = null;
        }

        private void doAddInvoiceRow(bool useMasoMoi)
        {
            if (string.IsNullOrEmpty(cbMaSo.Text) && useMasoMoi == false)
            {
                return;
            }

            if (string.IsNullOrEmpty(cbMaSoMoi.Text) && useMasoMoi)
            {
                return;
            }

            if (useMasoMoi && cbMaSoMoi.Text.StartsWith("NV"))
            {
                doProcessStaffSeller(cbMaSoMoi.Text);
                return;
            }

            if (!useMasoMoi && cbMaSo.Text.StartsWith("NV"))
            {
                doProcessStaffSeller(cbMaSo.Text);
                return;
            }


            if (useMasoMoi && (cbMaSoMoi.Text.StartsWith("CB") || cbMaSoMoi.Text.StartsWith("CW") || cbMaSoMoi.Text.StartsWith("CG")))
            {
                doProcessCustomerService(cbMaSoMoi.Text);
                return;
            }

            if (!useMasoMoi && (cbMaSo.Text.StartsWith("CB") || cbMaSo.Text.StartsWith("CW") || cbMaSo.Text.StartsWith("CG")))
            {
                doProcessCustomerService(cbMaSo.Text);
                return;
            }


            ItemEntity item = null;
            currentSelectedItem = null;
            if (useMasoMoi)
            {
                item = Database.getItemInStockByAutoKey(cbMaSoMoi.Text.Trim());
                if (item != null)
                {
                    cbMaSo.Text = item.id.ToUpper();
                }
                else
                {
                    cbMaSo.Text = string.Empty;
                }
            }
            else
            {
                string mso = cbMaSo.Text.Trim().ToUpper();
                cbMaSo.Text = mso;
                item = Database.getItemInStock(cbMaSo.Text.Trim());
                if (item != null)
                {
                    cbMaSoMoi.Text = item.autoKey.ToString();
                }
                else
                {
                    cbMaSoMoi.Text = string.Empty;
                }
            }


            if (item != null)
            {
                currentSelectedItem = item;
                txtName.Text = item.name;
                txtPrice.Text = item.price.ToString("#,0");
                decimal money = item.price * txtAmount.Value;
                txtMoney.Text = money.ToString("#,0");
                txtTonKho.Text = item.amount.ToString();
                if (item.amount <= 0)
                {
                    lbStatus.Text = "Hết hàng";
                    lbStatus.Tag = item.id;
                }
                else
                {
                    lbStatus.Text = string.Empty;
                    lbStatus.Tag = null;
                }

                if (chUseBarCode.Checked)
                {
                    try
                    {
                        doAdd();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
            else
            {
                txtName.Text = string.Empty;
                txtPrice.Text = "0";
                txtMoney.Text = "0";
                txtTonKho.Text = string.Empty;
                lbStatus.Text = string.Empty;
            }
        }

        private void txtAmount_ValueChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtPrice.Text))
            {
                int price;
                Int32.TryParse(txtPrice.Text.Replace(".", ""), out price);
                decimal money = price * txtAmount.Value;
                txtMoney.Text = money.ToString("#,0");
            }
        }

        private void doAdd()
        {
            try
            {
                if (string.IsNullOrEmpty(cbMaSo.Text))
                {
                    return;
                }

                if (cbCheckSLT.Checked && !string.IsNullOrEmpty(lbStatus.Text))
                {
                    return;
                }

                string maso = cbMaSo.Text.Trim();
                string barcode = cbMaSoMoi.Text.Trim();
                decimal discount = 0;
                ItemEntity selectedItem = (ItemEntity)itemCache[maso];
                if (selectedItem == null)
                {
                    selectedItem = Database.getItemInStock(maso);
                    if (selectedItem != null)
                    {
                        itemCache.Add(maso, selectedItem);
                    }
                    else
                    {
                        return;
                    }
                }

                decimal total = 0;
                int countItem = 0;
                DataRow row = (DataRow)itemRowCache[maso];
                if (row != null)
                {
                    int amount = Int32.Parse(row["amount"].ToString());
                    double price = Double.Parse(row["price"].ToString());
                    discount = getDiscount();
                    amount = amount + (int)txtAmount.Value;
                    if (selectedItem != null)
                    {
                        if (selectedItem.amount < amount)
                        {
                            if (cbCheckSLT.Checked)
                            {
                                lbStatus.Text = "Không đủ hàng !";
                                lbStatus.Tag = maso;
                                return;
                            }
                        }
                        else
                        {
                            lbStatus.Text = string.Empty;
                            lbStatus.Tag = null;
                        }
                    }
                    row["amount"] = amount.ToString();
                    row["money"] = (decimal)(amount * price);
                    total = 0;
                    foreach (DataRow r in invoiceData.Rows)
                    {
                        decimal m = decimal.Parse(r["money"].ToString());
                        total += m;

                        int am = Int32.Parse(r["amount"].ToString());
                        countItem += am;
                    }

                    totalMoneyInBill = total;
                    discount = getDiscount();
                    txtCK.Value = discount;
                    txtTotal.Value = total - (total * discount / 100);
                    txtDiscountValue.Value = (total * discount / 100);
                    lbTotalItem.Text = string.Format("Tổng s.phẩm:{0} cái", countItem);
                    return;
                }

                if (selectedItem != null)
                {

                    if (selectedItem.amount < txtAmount.Value || selectedItem.amount <= 0)
                    {
                        if (cbCheckSLT.Checked)
                        {
                            lbStatus.Text = "Không đủ hàng !";
                            lbStatus.Tag = maso;
                            return;
                        }
                    }
                    else
                    {
                        lbStatus.Text = string.Empty;
                        lbStatus.Tag = null;
                    }
                }

                total = 0;
                row = invoiceData.NewRow();
                itemRowCache.Add(maso, row);

                row["autoKey"] = barcode;
                row["itemId"] = maso;
                row["itemName"] = txtName.Text;
                row["amount"] = txtAmount.Value;
                row["ck"] = discount;
                if (!string.IsNullOrEmpty(txtPrice.Text))
                {
                    row["price"] = txtPrice.Text.Replace(".", "");
                }

                if (!string.IsNullOrEmpty(txtMoney.Text))
                {
                    string sMoney = txtMoney.Text.Replace(".", "");
                    decimal tt = Int32.Parse(sMoney);
                    row["money"] = tt;
                }

                invoiceData.Rows.Add(row);


                foreach (DataRow r in invoiceData.Rows)
                {
                    string sm = r["money"].ToString();
                    if (!string.IsNullOrEmpty(sm))
                    {
                        int m = Int32.Parse(r["money"].ToString());
                        total += m;
                    }

                    string sAmount = r["amount"].ToString();
                    if (!string.IsNullOrEmpty(sAmount))
                    {
                        int am = Int32.Parse(sAmount);
                        countItem += am;
                    }
                }

                totalMoneyInBill = total;
                discount = getDiscount();
                txtCK.Value = discount;
                txtTotal.Value = total - (total * discount / 100);
                txtDiscountValue.Value = (total * discount / 100);
                lbTotalItem.Text = string.Format("Tổng s.phẩm:{0} cái", countItem);
                dataGridView.Sort(dataGridView.Columns["total"], ListSortDirection.Ascending);
            }
            finally
            {
                //cbMaSo.Text = string.Empty;
                //cbMaSoMoi.Text = string.Empty;
            }
        }

        private void btAdd_Click(object sender, EventArgs e)
        {
            try
            {
                doAdd();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void checkAuto_CheckedChanged(object sender, EventArgs e)
        {
            this.txtPrice.ReadOnly = checkAuto.Checked;
            this.txtName.ReadOnly = checkAuto.Checked;
            //this.txtMoney.ReadOnly = checkAuto.Checked;
            if (this.checkAuto.Checked == true)
            {
                try
                {
                    ItemEntity item = currentSelectedItem;
                    if (item != null)
                    {
                        txtPrice.Text = item.price.ToString("#,0");
                        decimal t = item.price * txtAmount.Value;
                        txtMoney.Text = t.ToString("#,0");
                    }
                }
                catch (Exception)
                {
                }
            }
        }

        private void btDelete_Click(object sender, EventArgs e)
        {
            DataRowView rowView = bindingSource.Current as DataRowView;
            if (rowView != null)
            {
                string itemId = rowView.Row["itemId"].ToString();
                if (lbStatus.Tag != null && string.Compare(itemId, lbStatus.Tag.ToString(), true) == 0)
                {
                    lbStatus.Text = string.Empty;
                    lbStatus.Tag = null;
                    cbMaSo.Text = string.Empty;
                    btAdd.Enabled = true;

                }
                itemRowCache.Remove(itemId);
                rowView.Delete();
                txtName.Text = string.Empty;
                txtAmount.Value = 1;
                txtPrice.Text = string.Empty;
                txtMoney.Text = string.Empty;
                txtTonKho.Text = string.Empty;
                cbMaSo.Text = string.Empty;
                cbMaSoMoi.Text = string.Empty;

            }

            if (invoiceData.Rows.Count <= 0)
            {
                txtCustomerMoney.Text = string.Empty;
                txtMoneyReturn.Text = string.Empty;
                txtTotal.Text = string.Empty;
                lbTotalItem.Text = string.Format("Tổng s.phẩm:{0} cái", 0);
                return;
            }

            decimal total = 0;
            int countItem = 0;
            foreach (DataRow r in invoiceData.Rows)
            {
                string sm = r["money"].ToString();
                if (!string.IsNullOrEmpty(sm))
                {
                    int m = Int32.Parse(r["money"].ToString());
                    total += m;

                    int am = Int32.Parse(r["amount"].ToString());
                    countItem += am;
                }
            }

            totalMoneyInBill = total;
            decimal discount = getDiscount();
            txtCK.Value = discount;
            txtTotal.Value = total - (total * discount / 100);
            txtDiscountValue.Value = total * discount / 100;
            lbTotalItem.Text = string.Format("Tổng s.phẩm:{0} cái", countItem);
            dataGridView.Sort(dataGridView.Columns["total"], ListSortDirection.Ascending);


        }

        private void doShowPrintPreview()
        {
            try
            {
                if (frmPrintView == null)
                {
                    frmPrintView = new FrmPrintBillPreview();
                    frmPrintView.StartPosition = FormStartPosition.CenterScreen;
                    frmPrintView.Show(this);
                    Graphics g = Graphics.FromHwnd(frmPrintView.view.Handle);
                    paintView(g);
                    frmPrintView.Update();
                }
                else
                {
                    try
                    {
                        frmPrintView.Dispose();
                        frmPrintView = new FrmPrintBillPreview();
                        frmPrintView.StartPosition = FormStartPosition.CenterScreen;
                        frmPrintView.Show(this);
                        Graphics g = Graphics.FromHwnd(frmPrintView.view.Handle);
                        paintView(g);
                        frmPrintView.Update();
                    }
                    catch (Exception)
                    {
                    }

                }

                Bitmap bm = new Bitmap(291, 460);
                Graphics g2 = Graphics.FromImage(bm);
                g2.FillRectangle(Brushes.White, 0, 0, 291, 460);
                paintView(g2);
                g2.Dispose();
                string savePath = Path.Combine(BackupUtil.doCheckFolderInvoice(), masoHD + ".png");
                bm.Save(savePath, ImageFormat.Png);
                bm.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private decimal getDiscount()
        {
            decimal discount = 0;
            if (checkCK.Checked)
            {
                updateTotalMoneyInBill();
                if (rdPercent.Checked)
                {
                    discount = txtCK.Value;
                    if (txtMoneyBalance.Value > 0 && totalMoneyInBill > 0)
                    {
                        discount = (txtMoneyBalance.Value * 100) / totalMoneyInBill;
                    }
                }
                else
                {
                    if (txtMoneyDiscount.Value > 0 && totalMoneyInBill > 0)
                    {
                        discount = (txtMoneyDiscount.Value * 100) / totalMoneyInBill;
                    }
                }
            }

            return discount;
        }

        private void doCashBill()
        {
            string seller = cbSeller.Text;
            if (string.IsNullOrEmpty(seller))
            {
                MessageBox.Show(@"Không tìm thấy tên người bán hàng");
                return;
            }

            if (invoiceData.Rows.Count == 0)
            {
                return;
            }

            if (cbCheckSLT.Checked && !string.IsNullOrEmpty(lbStatus.Text))
            {
                return;
            }




            ArrayList rowList = new ArrayList();
            decimal discount = getDiscount();
            foreach (DataRow r in invoiceData.Rows)
            {
                ItemEntity item = (ItemEntity)itemCache[r["itemId"].ToString()];
                InvoiceRowEntity invoiceRow = new InvoiceRowEntity();
                invoiceRow.itemId = r["itemId"].ToString();
                invoiceRow.itemName = r["itemName"].ToString();
                invoiceRow.price = Int32.Parse(r["price"].ToString());
                invoiceRow.amount = Int32.Parse(r["amount"].ToString());
                invoiceRow.total = invoiceRow.price * invoiceRow.amount;
                invoiceRow.ck = discount;
                rowList.Add(invoiceRow);
                if (item != null)
                {
                    item.amount -= invoiceRow.amount;
                    if (item.amount < 0)
                    {
                        item.amount = 0;
                    }
                }
            }

            string createDate = dateTimePicker.Value.ToString("yyyy-MM-dd hh:mm:ss");
            if (cbChangeDate.Checked == false)
            {
                createDate = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            }
            long msoHD = Database.createInvoiceBuying(createDate, seller, "customer", rowList, discount);
            if (msoHD > 0)
            {
                masoHD = msoHD.ToString();
                lbMSHD.Text = "MSHĐ:" + masoHD;
                // print ...
                if (!cbPrint.Checked)
                {
                    try
                    {
                        this.Enabled = false;
                        doc.Print();
                        Bitmap bm = new Bitmap(291, 460);
                        Graphics g = Graphics.FromImage(bm);
                        g.FillRectangle(Brushes.White, 0, 0, 291, 460);
                        paintView(g);
                        g.Dispose();
                        string savePath = Path.Combine(BackupUtil.doCheckFolderInvoice(), masoHD + ".png");
                        bm.Save(savePath, ImageFormat.Png);
                        bm.Dispose();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    finally
                    {
                        this.Enabled = true;
                    }
                }
                else
                {
                    doShowPrintPreview();
                }

            }

            try
            {
                if (currentCustomer != null)
                {
                    int point = (int)(totalMoneyInBill / 1000);
                    Database.updatePoint4Customer(currentCustomer, (int)msoHD, point);
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                currentCustomer = null;
            }

            masoHD = string.Empty;
            itemRowCache.Clear();
            itemRowCache = new Hashtable();
            invoiceData.Clear();
            txtAmount.Value = 1;
            cbMaSo.Text = string.Empty;
            cbMaSoMoi.Text = string.Empty;
            txtPrice.Text = "0";
            txtName.Text = string.Empty;
            txtTonKho.Text = string.Empty;
            txtMoney.Text = "0";
            txtTotal.Value = 0;
            totalMoneyInBill = 0;
            lbStatus.Text = string.Empty;
            lbStatus.Tag = null;
            txtCustomerMoney.Text = string.Empty;
            txtMoneyReturn.Text = string.Empty;
            checkCK.Checked = false;
            txtCK.Value = 0;
            txtMoneyDiscount.Value = 0;
            txtMoneyBalance.Value = 0;
            lbTotalItem.Text = string.Format("Tổng s.phẩm:{0} cái", 0);
            txtTotal.Value = 0;

        }

        private void btDone_Click(object sender, EventArgs e)
        {
            if (checkCK.Checked)
            {
                if (rdPercent.Checked && txtMoneyBalance.Value > 0 && txtMoneyBalance.Value < txtDiscountValue.Value)
                {
                    MessageBox.Show("Giá trị làm tròn chỉ được phép làm tròn lên, không làm tròn xuống.");
                    return;
                }
            }
            updateTotalMoneyInBill();
            doCashBill();
            txtMoneyBalance.Value = 0;
            checkCK.Checked = false;
            cbPrint.Checked = false;
        }

        void doc_PrintPage(object sender, PrintPageEventArgs e)
        {
            Graphics g = e.Graphics;
            paintView(g);
        }


        private void paintView(Graphics g)
        {
            // Paint header :
            float lineSep = 5;
            int lineW = 270;
            float fontH = fontHeader.GetHeight(g);
            float fontB = fontBody.GetHeight(g);
            float fontF = fontFooter.GetHeight(g);
            RectangleF rectF1 = new RectangleF(5, 5, lineW, fontH);
            StringFormat format = new StringFormat();
            format.Alignment = StringAlignment.Center;
            g.DrawString("*** CÀ LEM ***", fontHeader, Brushes.Black, rectF1, format);
            float y = lineSep + fontH + 15;

            rectF1 = new RectangleF(5, y, lineW, fontH);
            g.DrawString("THỜI TRANG TRẺ EM", fontHeader, Brushes.Black, rectF1, format);

            y += fontH + lineSep;
            rectF1 = new RectangleF(5, y, lineW, 3 * fontF);
            g.DrawString("197 Phan Đình Phùng, P.Thanh Bình TP.Biên Hòa", fontFooter, Brushes.Black, rectF1, format);
            y += fontH + 3 * lineSep;
            rectF1 = new RectangleF(5, y, lineW, fontF);
            g.DrawString("***************************", fontFooter, Brushes.Black, rectF1, format);
            rectF1 = new RectangleF(5, y + fontH, lineW, fontF);
            format.Alignment = StringAlignment.Near;
            g.DrawString("MSHĐ :" + masoHD, fontFooterBold, Brushes.Black, rectF1, format);
            format.Alignment = StringAlignment.Far;
            if (cbChangeDate.Checked)
            {
                g.DrawString(dateTimePicker.Value.ToString("dd-MM-yyyy HH:mm"), fontFooter, Brushes.Black, rectF1, format);
            }
            else
            {
                DateTime d = DateTime.Now;
                g.DrawString(d.ToString("dd-MM-yyyy HH:mm"), fontFooter, Brushes.Black, rectF1, format);
            }
            y += fontH + 3 * lineSep;
            // Draw Invoice row
            //------------------------------------------------------------------------------
            float x = 4;
            lineW = 275;
            y += fontH + 2 * lineSep;
            string tab4 = "    ";
            string tab8 = "        ";
            RectangleF rectBody = new RectangleF(x, y, lineW, fontB);
            format.Alignment = StringAlignment.Near;
            g.DrawString("Mã S.Phẩm" + tab4 + "  SL" + tab8 + "Giá" + tab8 + "      T.Tiền", fontFooter, Brushes.Black, rectBody, format);
            g.DrawLine(Pens.Black, x, y + fontB, lineW, y + fontB);
            y += fontH + lineSep;

            RectangleF rectC1 = new RectangleF(x, y, 75, fontB);
            RectangleF rectC2 = new RectangleF(x + rectC1.Width + 2, y, 30, fontB);
            RectangleF rectC3 = new RectangleF(rectC2.X + rectC2.Width + 2, y, 75, fontB);
            RectangleF rectC4 = new RectangleF(rectC3.X + rectC3.Width + 2, y, 90, fontB);
            int index = 0;
            int sumAmount = 0;
            foreach (DataRow r in invoiceData.Rows)
            {
                index++;
                InvoiceRowEntity invoiceRow = new InvoiceRowEntity();
                invoiceRow.itemId = r["itemId"].ToString();
                invoiceRow.itemName = r["itemName"].ToString();
                invoiceRow.price = Int32.Parse(r["price"].ToString());
                invoiceRow.amount = Int32.Parse(r["amount"].ToString());
                invoiceRow.total = invoiceRow.price * invoiceRow.amount;
                sumAmount += invoiceRow.amount;

                format.Alignment = StringAlignment.Far;
                g.DrawString(invoiceRow.amount.ToString(), fontFooter, Brushes.Black, rectC2, format);
                format.Alignment = StringAlignment.Near;
                //g.DrawString(invoiceRow.itemId, fontFooter, Brushes.Black, rectC1, format);
                g.DrawString(r["autoKey"].ToString(), fontFooter, Brushes.Black, rectC1, format);
                format.Alignment = StringAlignment.Far;
                g.DrawString(invoiceRow.price.ToString("#,0"), fontFooter, Brushes.Black, rectC3, format);
                g.DrawString(invoiceRow.total.ToString("#,0"), fontFooter, Brushes.Black, rectC4, format);

                //g.DrawRectangle(Pens.Black, Rectangle.Round(rectC1));
                //g.DrawRectangle(Pens.Black, Rectangle.Round(rectC2));
                //g.DrawRectangle(Pens.Black, Rectangle.Round(rectC3));
                //g.DrawRectangle(Pens.Black, Rectangle.Round(rectC4));

                rectC1.Y += fontB + lineSep;
                rectC2.Y = rectC1.Y;
                rectC3.Y = rectC1.Y;
                rectC4.Y = rectC1.Y;
            }

            g.DrawLine(Pens.Black, rectC1.X, rectC1.Y, lineW, rectC1.Y);
            // Ve sum cot so luong.
            rectC2.Y += 5;
            format.Alignment = StringAlignment.Far;
            g.DrawString(sumAmount.ToString(), fontFooter, Brushes.Black, rectC2, format);
            // ----------------------------------------------------------------
            rectC3.Y += 5;
            //format.Alignment = StringAlignment.Far;
            if (checkCK.Checked && txtCK.Value > 0)
            {
                g.DrawString("Tổng:", fontFooter, Brushes.Black, rectC3, format);
            }
            else
            {
                g.DrawString("Tổng:", fontFooterBold, Brushes.Black, rectC3, format);
            }
            rectC4.Y = rectC3.Y;
            format.Alignment = StringAlignment.Far;
            //g.DrawString(txtTotal.Text, fontFooterBold, Brushes.Black, rectC4, format);
            g.DrawString(totalMoneyInBill.ToString("#,0"), fontFooterBold, Brushes.Black, rectC4, format);

            if (checkCK.Checked && txtCK.Value > 0)
            {
                rectC3.Y += 5 + fontB;
                format.Alignment = StringAlignment.Near;
                RectangleF recDiscount = new RectangleF(rectC3.X, rectC3.Y, rectC3.Width + 20, rectC3.Height);
                g.DrawString(string.Format(@"Giảm {0}%", txtCK.Value.ToString("#.##")), fontFooter, Brushes.Black, recDiscount, format);
                rectC4.Y = rectC3.Y;
                format.Alignment = StringAlignment.Far;
                decimal discount = totalMoneyInBill * txtCK.Value / 100;
                g.DrawString(discount.ToString("#,0"), fontFooterBold, Brushes.Black, rectC4, format);

                rectC3.Y += 5 + fontB;
                format.Alignment = StringAlignment.Near;
                g.DrawString("T.Tiền:", fontFooterBold, Brushes.Black, rectC3, format);
                rectC4.Y = rectC3.Y;
                format.Alignment = StringAlignment.Far;
                g.DrawString(txtTotal.Text, fontFooterBold, Brushes.Black, rectC4, format);
            }

            rectC4.Y += 100;
            RectangleF rectFooter = new RectangleF(5, rectC4.Y, lineW, fontH);
            format.Alignment = StringAlignment.Center;
            g.DrawString("***** ***** ", fontFooter, Brushes.Black, rectFooter, format);
            rectFooter.Y += fontF + lineSep;
            g.DrawString("Hotline: 0168.448.2490 ", fontFooter, Brushes.Black, rectFooter, format);
            rectFooter.Y += fontF + lineSep;
            g.DrawString("www.facebook.com/Baby.Kutee.Shop", fontFooter, Brushes.Black, rectFooter, format);
            rectFooter.Y += fontF + lineSep;
            g.DrawString("Nhân viên:" + cbSeller.Text, fontFooter, Brushes.Black, rectFooter, format);
            rectFooter.Y += fontF + 2 * lineSep;
            g.DrawString("----", fontFooter, Brushes.Black, rectFooter, format);
            g.Dispose();

        }

        private void btTraHang_Click(object sender, EventArgs e)
        {
            FrmConfirmReturnItem confirm = new FrmConfirmReturnItem();
            if (confirm.ShowDialog(this) == DialogResult.Cancel)
            {
                return;
            }

            string seller = cbSeller.Text;
            string reason = confirm.txtReason.Text;
            if (string.IsNullOrEmpty(seller))
            {
                MessageBox.Show(@"Không tìm thấy tên người bán hàng");
                return;
            }

            if (invoiceData.Rows.Count == 0)
            {
                return;
            }

            decimal discount = getDiscount();
            ArrayList rowList = new ArrayList();
            foreach (DataRow r in invoiceData.Rows)
            {
                ItemEntity item = (ItemEntity)itemCache[r["itemId"].ToString()];
                InvoiceRowEntity invoiceRow = new InvoiceRowEntity();
                invoiceRow.itemId = r["itemId"].ToString();
                invoiceRow.itemName = r["itemName"].ToString();
                invoiceRow.price = Int32.Parse(r["price"].ToString());
                invoiceRow.amount = Int32.Parse(r["amount"].ToString());
                invoiceRow.total = invoiceRow.price * invoiceRow.amount;
                invoiceRow.ck = discount;
                rowList.Add(invoiceRow);
                if (item != null)
                {
                    item.amount += invoiceRow.amount;
                }
            }

            long msoHD = Database.createInvoiceReturning(seller, "customer", reason, rowList);
            if (msoHD > 0)
            {
                masoHD = msoHD.ToString();
                lbMSHD.Text = "MSHĐ:" + masoHD;
                showMessage("Trả hàng thành công, Hóa đơn trả hàng số : " + msoHD);
            }

            itemRowCache.Clear();
            itemRowCache = new Hashtable();
            invoiceData.Clear();
            txtAmount.Value = 1;
            masoHD = string.Empty;
            cbMaSo.Text = string.Empty;
            cbMaSoMoi.Text = string.Empty;
            txtPrice.Text = "0";
            txtName.Text = string.Empty;
            txtMoney.Text = "0";
            txtTotal.Text = "0";
            lbStatus.Text = string.Empty;
            txtTonKho.Text = string.Empty;
            lbStatus.Tag = null;
            checkCK.Checked = false;
            txtCK.Value = 0;
            totalMoneyInBill = 0;
            txtTotal.Value = 0;
            txtDiscountValue.Value = 0;
            txtMoneyBalance.Value = 0;
        }

        private void btClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        private void showMessage(string message)
        {
            FrmMain main = (FrmMain)this.MdiParent;
            main.doShowMessage("Thông báo", message);
        }

        private void txtPrice_TextChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtPrice.Text) || txtPrice.Text.Equals("0"))
            {
                txtMoney.Text = "";
            }
            else
            {
                try
                {
                    string svalue = txtPrice.Text.Replace(".", "");
                    decimal t = txtAmount.Value * decimal.Parse(svalue);
                    txtMoney.Text = t.ToString("#,0");
                }
                catch (Exception)
                {
                }
            }
        }

        private void FrmSale_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.F2:
                    doAdd();
                    break;
                case Keys.F5:
                    doCashBill();
                    txtMoneyBalance.Value = 0;
                    checkCK.Checked = false;
                    break;
                case Keys.F12:
                    chUseBarCode.Checked = true;
                    break;
            }
        }

        private void cbChangeDate_CheckedChanged(object sender, EventArgs e)
        {
            dateTimePicker.Enabled = cbChangeDate.Checked;
        }

        private void checkCK_CheckedChanged(object sender, EventArgs e)
        {
            this.scheduleFocus.Enabled = !checkCK.Checked;
            this.txtCK.Enabled = checkCK.Checked;
            txtMoneyDiscount.Enabled = checkCK.Checked;
            txtMoneyBalance.Enabled = false;
            rdMoney.Enabled = checkCK.Checked;
            rdPercent.Enabled = checkCK.Checked;
            if (checkCK.Checked)
            {
                updateTotalMoneyInBill();
                if (rdPercent.Checked)
                {
                    txtMoneyBalance.Enabled = true;
                    this.txtMoneyDiscount.Enabled = false;
                }
                else
                {
                    txtMoneyBalance.Enabled = false;
                    txtCK.Enabled = false;
                    this.txtMoneyDiscount.Enabled = true;
                }

                if (dataGridView.RowCount > 0)
                {
                    try
                    {
                        decimal ck = txtCK.Value;
                        decimal discount = ck * totalMoneyInBill / 100;
                        decimal t = (decimal)(totalMoneyInBill - discount);
                        txtTotal.Text = t.ToString("#,0");
                        txtDiscountValue.Value = discount;
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
            else
            {
                updateTotalMoneyInBill();
                txtTotal.Value = totalMoneyInBill;

            }


        }

        private void txtCK_ValueChanged(object sender, EventArgs e)
        {
            try
            {
                if (rdPercent.Checked)
                {
                    decimal ck = txtCK.Value;
                    updateTotalMoneyInBill();
                    decimal discount = ck * totalMoneyInBill / 100;
                    if (txtMoneyBalance.Value > 0)
                    {
                        discount = txtMoneyBalance.Value;
                    }

                    decimal t = (decimal)(totalMoneyInBill - discount);
                    txtTotal.Text = t.ToString("#,0");
                    txtDiscountValue.Text = discount.ToString("#,0");
                }
            }
            catch (Exception ex)
            {
            }
        }

        private void updateTotalMoneyInBill()
        {
            if (dataGridView.RowCount == 0)
            {
                totalMoneyInBill = 0;
                return;
            }

            totalMoneyInBill = 0;
            try
            {
                foreach (DataRow r in invoiceData.Rows)
                {
                    totalMoneyInBill += decimal.Parse(r["money"].ToString());
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        private void txtMoneyDiscount_ValueChanged(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView.RowCount > 0)
                {
                    if (rdMoney.Checked)
                    {
                        txtCK.Value = getDiscount();
                        txtDiscountValue.Value = totalMoneyInBill * txtCK.Value / 100;
                        txtTotal.Value = totalMoneyInBill - txtMoneyDiscount.Value;

                    }
                }
            }
            catch (Exception)
            {
            }
        }

        private void rdMoney_CheckedChanged(object sender, EventArgs e)
        {
            this.txtMoneyDiscount.Enabled = rdMoney.Checked;
            if (rdMoney.Checked)
            {
                this.txtDiscountValue.Enabled = false;
                txtMoneyBalance.Enabled = false;
                txtCK.Enabled = false;
                txtCK.Value = getDiscount();
                txtDiscountValue.Value = (totalMoneyInBill * txtCK.Value / 100);
                decimal t = totalMoneyInBill - txtDiscountValue.Value;

                txtTotal.Text = t.ToString("#,0");
            }
        }

        private void rdPercent_CheckedChanged(object sender, EventArgs e)
        {
            this.txtMoneyDiscount.Enabled = false;
            txtCK.Enabled = true;
            if (rdPercent.Checked)
            {
                txtMoneyBalance.Enabled = true;
                txtCK.Value = getDiscount();
                decimal ck = txtCK.Value;
                decimal discount = ck * totalMoneyInBill / 100;
                decimal t = (decimal)(totalMoneyInBill - discount);
                txtTotal.Text = t.ToString("#,0");
                txtDiscountValue.Value = discount;
            }
        }

        private void txtMoneyBalance_ValueChanged(object sender, EventArgs e)
        {
            if (rdPercent.Checked)
            {
                decimal t = (decimal)(totalMoneyInBill - txtMoneyBalance.Value);
                txtTotal.Text = t.ToString("#,0");
            }
        }

        private void FrmSale_Activated(object sender, EventArgs e)
        {
            //if (this.chUseBarCode.Checked)
            //{
            //    this.cbMaSoMoi.Focus();
            //}
            //else
            //{
            //    this.cbMaSo.Focus();
            //}

            this.cbMaSoMoi.Focus();
        }

        private void scheduleFocus_Tick(object sender, EventArgs e)
        {
            if (this.chUseBarCode.Checked && isActiveFrom)
            {
                if (!this.cbMaSoMoi.Focused)
                {
                    this.cbMaSoMoi.Focus();
                }
            }
        }

        private void chUseBarCode_CheckedChanged(object sender, EventArgs e)
        {
            if (chUseBarCode.Checked)
            {
                this.cbMaSoMoi.Focus();
            }
        }

        private void cbMaSo_Enter(object sender, EventArgs e)
        {
            chUseBarCode.Checked = false;
        }

        private void FrmSale_Leave(object sender, EventArgs e)
        {
            isActiveFrom = false;
        }

        private void FrmSale_Enter(object sender, EventArgs e)
        {
            isActiveFrom = true;
        }

        private void txtCustomerMoney_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
            if (e.KeyChar == (char)13)
            {
                scheduleFocus.Enabled = true;
                cbMaSoMoi.Focus();
                string value = txtCustomerMoney.Text;
                if (value.Length <= 3)
                {
                    value = value + "000";
                }

                decimal num = 0;
                Decimal.TryParse(value, out num);
                if (totalMoneyInBill < num)
                {
                    txtMoneyReturn.Text = (num - totalMoneyInBill).ToString("#,0");
                }
            }
        }

        private void txtCustomerMoney_Enter(object sender, EventArgs e)
        {
            txtCustomerMoney.Text = string.Empty;
            scheduleFocus.Enabled = false;
        }
    }
}
